<script setup>
import { ref } from 'vue'
import { getUserInfoAPI, addOrUpdateUserAPI, getAllRolesAPI, setUserRoleAPI, removeUserAPI, removeSelectUserAPI } from '@/api/acl/user'
import { ElMessage } from 'element-plus'
import { nextTick } from 'vue'
import { useLayoutSettingStore } from '@/store/modules/setting'

const layoutSettingStore = useLayoutSettingStore()

const currentPage = ref(1)

const pageSize = ref(5)

const total = ref(0)

const userArr = ref([])

// 定义响应式数据：收集用户输入的搜索关键字
const keyword = ref('')

// 获取全部已有用户信息
const getHasUser = async (pager = 1) => {
  currentPage.value = pager
  let res = await getUserInfoAPI(currentPage.value, pageSize.value, keyword.value)
  if(res.code === 200) {
    userArr.value = res.data.records
    total.value = res.data.total
  }
}

getHasUser()

const handlerSizeChange = () => {
  getHasUser()
}

// 添加与编辑角色抽屉的显隐控制
const editOrAddUser = ref(false)

// 收集用户信息的响应式数据
const userParams = ref({
  username: '',
  name: '',
  password: ''
})

// 表单对象
const userForm = ref()

// 添加用户
const addUser = () => {
  editOrAddUser.value = true
  // 清空数据
  Object.assign(userParams.value, {
    username: '',
    name: '',
    password: '',
    id: 0
  })
  // 清除上一次的错误提示信息
  nextTick(() => {
    userForm.value.clearValidate('username')
    userForm.value.clearValidate('name')
    userForm.value.clearValidate('password')
  })
}



// 编辑用户信息
const updateUser = (row) => {
  editOrAddUser.value = true
  // 存储收集已有的用户信息
  Object.assign(userParams.value, row)
  // 清除上一次的错误提示信息
  nextTick(() => {
    userForm.value.clearValidate('username')
    userForm.value.clearValidate('name')
    userForm.value.clearValidate('password')
  })
}

// 保存按钮的回调
const save = async () => {
  await userForm.value.validate()
  let res = await addOrUpdateUserAPI(userParams.value)
  if(res.code === 200) {
    editOrAddUser.value = false
    ElMessage({
      type: 'success',
      message: userParams.value.id ? '修改成功' : '添加成功'
    })
    // getHasUser(userParams.value.id ? currentPage.value : 1)
    // 浏览器自动刷新一次,自动刷新后不需要再次获取数据，所以上方语句注释掉
    window.location.reload()
  } else {
    editOrAddUser.value = false
    ElMessage({
      type: 'error',
      message: userParams.value.id ? '修改失败' : '添加失败'
    })
  }
}

// 取消按钮的回调
const cancel = () => {
  editOrAddUser.value = false
}

// 校验用户名
const checkUsername = (rule, value, callback) => {
  // 用户名字至少为5位
  if (value.trim().length >= 5) {
    callback()
  } else {
    callback(new Error('用户名字至少五位'))
  }
}

// 校验用户昵称
const checkName = (rule, value, callback) => {
  // 用户昵称至少为5位
  if (value.trim().length >= 5) {
    callback()
  } else {
    callback(new Error('用户昵称至少五位'))
  }
}

// 校验用户密码
const checkPassword = (rule, value, callback) => {
  // 用户昵称至少为5位
  if (value.trim().length >= 6) {
    callback()
  } else {
    callback(new Error('用户密码至少六位'))
  }
}

// 表单校验规则
const rules = ref({
  username: [
    {required: true, validator: checkUsername, trigger: 'blur'}
  ],
  name: [
    { required: true, validator: checkName, trigger: 'blur' }
  ],
  password: [
    { required: true, validator: checkPassword, trigger: 'blur' }
  ]
})

// 控制角色分配抽屉的显隐
const editUserRole = ref(false)

// 全选角色
const checkAll = ref(false)

// 已选择角色
const checkRoles = ref([])

// 全部角色
const allRoles = ref([])

// 分配角色按钮的回调
const setRole = async (row) => {
  
  // 存储已有用户信息
  Object.assign(userParams.value, row)
  let res = await getAllRolesAPI(row.id)
  if(res.code === 200) {
    allRoles.value = res.data.allRolesList
    checkRoles.value = res.data.assignRoles
    editUserRole.value = true
  }
}

// 全选状态改变
const handleCheckAllChange = (value) => {
  checkRoles.value = value ? allRoles.value : []
}

// 单选状态改变
const handleCheckedChange = (value) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === allRoles.value.length
}

// 确定按钮
const confirmClick = async () => {
  let setRoleData = {
    userId: userParams.value.id,
    roleIdList: checkRoles.value.map(item => item.id)
  }
  let res = await setUserRoleAPI(setRoleData)
  if(res.code === 200) {
    ElMessage({
      type: 'success',
      message: '职位修改成功'
    })
    editUserRole.value = false
    getHasUser(currentPage.value)
  }
}

// 删除用户
const removeUser = async (userId) => {
  let res = await removeUserAPI(userId)
  if(res.code === 200) {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    getHasUser(userArr.value.length > 1 ? currentPage.value : currentPage.value - 1)
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败'
    })
  }
}

// 准备一个数组存储批量删除的id
const selectIdArr = ref([])

// table复选框勾选时触发的事件
const selectChange = (value) => {
  selectIdArr.value = value
}

// 批量删除按钮的回调
const deleteSelectUser = async () => {
  let idList = selectIdArr.value.map(item => item.id)
  let res = await removeSelectUserAPI(idList)
  if(res.code === 200) {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    getHasUser(userArr.value.length > 1 ? currentPage.value : currentPage.value - 1)
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败'
    })
  }
}

// 搜索按钮的回调
const search = () => {
  getHasUser()
  keyword.value = ''
}

// 重置按钮
const reset = () => {
  layoutSettingStore.refresh = !layoutSettingStore.refresh
}
</script>

<template>
  <div>
    <el-card style="height: 80px;">
      <el-form :inline="true" class="search_form">
        <el-form-item label="用户名:">
          <el-input v-model="keyword" style="width: 240px;" placeholder="请输入搜索用户名"  clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="default" :disabled="!keyword" @click="search">搜索</el-button>
          <el-button size="default" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card style="margin: 10px 0;">
      <el-button type="primary" size="default" @click="addUser">添加用户</el-button>
      <el-button type="danger" size="default" :disabled="!selectIdArr.length" @click="deleteSelectUser">批量删除</el-button>
      <el-table border style="margin: 10px 0;" :data="userArr" @select="selectChange">
        <el-table-column type="selection" align="center"></el-table-column>
        <el-table-column label="#" align="center" type="index"></el-table-column>
        <el-table-column label="ID" align="center" prop="id"></el-table-column>
        <el-table-column label="用户名字" align="center" prop="username" show-overflow-tooltip></el-table-column>
        <el-table-column label="用户名称" align="center" prop="name" show-overflow-tooltip></el-table-column>
        <el-table-column label="用户角色" align="center" prop="roleName" show-overflow-tooltip></el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" show-overflow-tooltip></el-table-column>
        <el-table-column label="更新时间" align="center" prop="updateTime" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" width="360px" align="center">
          <template #default="{row}">
            <el-button type="primary" size="default" icon="User" @click="setRole(row)">分配角色</el-button>
            <el-button type="primary" size="default" icon="Edit" @click="updateUser(row)">编辑</el-button>
            <el-popconfirm
            :title="`你确定要删除${row.username}吗？`"
            width="200"
            @confirm="removeUser(row.id)">
              <template #reference>
                <el-button type="primary" size="default" icon="Delete">删除</el-button>
              </template>
            </el-popconfirm>
            
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
      v-model:currentPage="currentPage"
      :page-sizes="[3, 5, 7, 9]"
      v-model:page-size="pageSize"
      layout="prev, pager, next, jumper, ->, sizes, total"
      :total="total"
      background
      @current-change="getHasUser"
      @size-change="handlerSizeChange">
      </el-pagination>
    </el-card>
    <!-- 抽屉结构:添加与修改用户 -->
    <el-drawer v-model="editOrAddUser" direction="rtl" size="30%">
      <template #header>
        <h4>{{ userParams.id ? '修改用户' : '添加用户' }}</h4>
      </template>
      <template #default>
        <el-form :model="userParams" :rules="rules" ref="userForm">
          <el-form-item label="用户姓名" prop="username">
            <el-input v-model="userParams.username" placeholder="请您输入用户姓名"></el-input>
          </el-form-item>
          <el-form-item label="用户昵称" prop="name">
            <el-input v-model="userParams.name" placeholder="请您输入用户昵称"></el-input>
          </el-form-item>
          <el-form-item label="用户密码" prop="password" v-if="!userParams.id">
            <el-input v-model="userParams.password" placeholder="请您输入用户密码"></el-input>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <el-button size="default" @click="cancel">取消</el-button>
        <el-button type="primary" size="default" @click="save">保存</el-button>
      </template>
    </el-drawer>
    <!-- 抽屉结构:用于对某一个已有的账号进行角色分配 -->
    <el-drawer v-model="editUserRole" direction="rtl" size="30%">
      <template #header>
          <h4>分配角色(职位)</h4>
        </template>
        <template #default>
          <el-form>
            <el-form-item label="用户姓名" :disabled="true">
              <el-input v-model="userParams.username" placeholder="请您输入用户姓名" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="角色列表">

              <el-checkbox
              v-model="checkAll"
              @change="handleCheckAllChange">
                全选
              </el-checkbox>
              <!-- 显示职位的复选框 -->
              <el-checkbox-group
              v-model="checkRoles"
              @change="handleCheckedChange">
                <el-checkbox v-for="(role) in allRoles" :key="role.id" :label="role.roleName" :value="role"></el-checkbox>
              </el-checkbox-group>

            </el-form-item>
          </el-form>
        </template>
        <template #footer>
          <el-button size="default" @click="editUserRole = false">取消</el-button>
          <el-button type="primary" size="default" @click="confirmClick">保存</el-button>
        </template>
    </el-drawer>
    
  </div>
</template>

<style scoped>
.search_form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
